<template>
  <div>
    <el-input
      v-model="inputValue"
      :placeholder="item.placeholder"
      readonly
      @click="show = true"
    >
      <template #suffix>
        <span v-if="item.clearable">
          <el-icon><ele-CircleClose /></el-icon>
        </span>
      </template>
    </el-input>
    <van-popup
      v-model:show="show"
      position="bottom"
      round
    >
      <van-cascader
        v-model:value="cascaderValue"
        :field-names="fieldNames"
        :options="getOptions()"
        :title="item.placeholder"
        active-color="#1890ff"
        @close="show = false"
        @finish="onFinish"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { Cascader, Popup } from "vant";
import { formEmits, formItemProps, useFormItem } from "@/views/formgen/components/FormItem/hooks/useFormItemHook";
import { findLabelsByIds } from "@/views/formgen/components/GenerateForm/FormItemLabel";

const props = defineProps({
  ...formItemProps
});

const emits = defineEmits([...formEmits, "changeLabel"]);

const { changeValue, getOptions } = useFormItem(props, emits, true);

watch(
  () => changeValue.value,
  val => {
    emits("changeLabel", findLabelsByIds(getOptions(), val));
  }
);

const inputValue = ref("");
const show = ref(false);
const cascaderValue = ref("");

const fieldNames = {
  text: "label",
  value: "value",
  children: "children"
};

const getLabels = (options, values) => {
  const arr = [];
  values.forEach(e => {
    if (!arr.length) {
      const item = options.find(op => op.value === e);
      arr.push(item);
    } else {
      const item = arr[arr.length - 1].children.find(op => op.value === e);
      arr.push(item);
    }
  });
  return arr;
};

const onClear = () => {
  changeValue.value = [];
  cascaderValue.value = "";
  inputValue.value = "";
};

const setInputValue = selectedOptions => {
  const showAllLevels = props.item["show-all-levels"];
  const vals = selectedOptions.map(e => e.label);
  inputValue.value = showAllLevels ? vals.join("/") : selectedOptions[selectedOptions.length - 1].label;
};

const onFinish = e => {
  const { selectedOptions } = e;
  changeValue.value = selectedOptions.map(e => e.value);
  setInputValue(selectedOptions);
  show.value = false;
};

watch(
  () => changeValue.value,
  val => {
    emits("changeLabel", findLabelsByIds(getOptions(), val));
  },
  { deep: true }
);

onMounted(() => {
  if (changeValue.value) {
    cascaderValue.value = changeValue.value[changeValue.value.length - 1];
    if (changeValue.value.length) {
      const arr = getLabels(getOptions(), changeValue.value);
      setInputValue(arr);
    }
  }
});
</script>
